
package com.aizhixin.lab.task.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.aizhixin.lab.config.Config;
import com.aizhixin.lab.course.course.entity.CourseChapter;
import com.aizhixin.lab.course.course.service.CoursePublishService;
import com.aizhixin.lab.course.course.service.CourseService;
import com.aizhixin.lab.task.domain.*;
import com.aizhixin.lab.task.entity.ReleaseTaskQuestion;
import com.aizhixin.lab.task.service.TaskStuInforService;
import io.swagger.annotations.ApiModelProperty;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.account.service.AccountService;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.utils.TokenUtil;
import com.aizhixin.lab.course.course.entity.Course;
import com.aizhixin.lab.task.entity.ReleaseTask;
import com.aizhixin.lab.task.entity.Task;
import com.aizhixin.lab.task.entity.TaskQuestion;
import com.aizhixin.lab.task.service.ReleaseTaskQuestionsService;
import com.aizhixin.lab.task.service.ReleaseTaskService;
import com.aizhixin.lab.task.service.TaskQuestionsService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import javax.servlet.http.HttpServletResponse;

/**
 * @author xiagen
 * @ClassName: WorkReleaseControllerV2
 * @Description:
 * @date 2017年6月7日 下午3:10:01
 */
@RestController
@RequestMapping("/api/v1/task")
@Api(value = "发布任务操作API", description = "发布任务操作API")
public class TaskReleaseController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private TaskQuestionsService taskQuestionService;
    @Autowired
    private ReleaseTaskService releaseTaskService;
    @Autowired
    private ReleaseTaskQuestionsService releaseTaskQuestionsService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private CoursePublishService coursePublishService;
    @Autowired
    private Config config;
    @Autowired
    private TaskStuInforService taskStuInforService;

    @RequestMapping(value = "/release", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "发布任务", httpMethod = "POST", notes = "发布任务<br><br><b>zhengning</b>")
    public ResponseEntity<?> workRelease(@RequestHeader("Authorization") String token,
                                         @ApiParam(value = "<b>必填</b><br>taskId:任务id<br>taskName:发布任务名称<br>courseId:课程id<br>templateId:模板id<br>scoringMethod:计分方式(0:五级九段制(默认),1:百分制,2:两级制)<br>") @RequestBody ReleaseTaskDomain domain) {
        Map<String, Object> result = new HashMap<String, Object>();
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        } else {
            domain.setCreator(account.getId());
        }
        if (StringUtils.isEmpty(domain.getTaskId())) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "发布的任务id不能为空");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }

        if (StringUtils.isEmpty(domain.getCourseId())) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "发布的任务的课程id不能为空");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        if (domain.getClassIdArr().isEmpty()) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "发布的任务的班级classId集合不能为空");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        if (domain.getCourseChapterId() <= 0L || domain.getCourseChapterId() == null) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "发布的任务的课程章节ID不能为空");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
//        if (domain.getCourseMinutiaId() <= 0L || domain.getCourseMinutiaId() == null) {
//            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
//            result.put(ApiReturnConstants.ERROR, "发布的任务的课程章节的小节ID不能为空");
//            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
//        }
        List<CourseChapter> minutiaList = coursePublishService.findMinutiaList(domain.getCourseChapterId());
        if (minutiaList.size() > 0 && (domain.getCourseMinutiaId() == 0 || domain.getCourseMinutiaId() == null)) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "发布的任务的课程小节ID不能为空");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        List<TaskQuestion> taskQuestionsList = taskQuestionService.getListTaskQuestion(domain.getTaskId());
        if (taskQuestionsList == null || taskQuestionsList.isEmpty()) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "任务没内容");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        } else {
            List<ReleaseTask> releaseTaskList = releaseTaskService.saveReleaseTask(domain, account);
            result.put(ApiReturnConstants.DATA, releaseTaskList);
            result.put(ApiReturnConstants.SUCCESS, Boolean.TRUE);
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }

    }

    @RequestMapping(value = "/getcourseclasslist", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "教师课程模板下班课列表", response = Void.class, notes = "教师课程模板下班课列表<br>@author zhengning")
    public ResponseEntity<?> getCourseClassList(
            @RequestHeader("Authorization") String token,
            @ApiParam(value = "templateId", required = true) @RequestParam(value = "templateId", required = true) Long templateId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity(releaseTaskService.findCourseClassList(templateId, account.getId()), HttpStatus.OK);
    }

    @RequestMapping(value = "/findreleasepage", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "分页查询发布任务列表", response = Void.class, notes = "分页查询发布任务列表<br>@author lwq")
    public ResponseEntity<?> findPage(
            @RequestHeader("Authorization") String token,
            @ApiParam(value = "courseId:备课课程id classId:班级Id", required = false) @RequestBody QueryTaskDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }

        Map<String, Object> result = new HashMap();
//		if (StringUtils.isEmpty(domain.getCourseId())) {
//			result.put(ApiReturnConstants.SUCCESS, false);
//			result.put(ApiReturnConstants.ERROR, "课程模板id不能为空！");
//			return new ResponseEntity(result, HttpStatus.OK);
//		}
        result = releaseTaskService.findReleaseTaskPage(domain, account.getId());
        if (result.get("data") == null) {
            return new ResponseEntity("没有发布任务", HttpStatus.OK);
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }


    @RequestMapping(value = "/delreleasetask", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "DELETE", value = "删除发布任务", response = Void.class, notes = "删除发布任务<br>@author zhengning")
    public ResponseEntity<?> delete(
            @RequestHeader("Authorization") String token,
            @ApiParam(value = "release_task_id 发布任务id") @RequestParam(value = "id", required = true) String id) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> result = new HashMap();
        if (StringUtils.isEmpty(id)) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "发布任务id不能为空！");
            return new ResponseEntity(result, HttpStatus.OK);
        }
        ReleaseTask task = releaseTaskService.findById(id);
        if (null != task) {
            task.setDeleteFlag(DataValidity.INVALID.getState());
            releaseTaskService.save(task);
            taskStuInforService.deleteReleaseTask(id);
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "id对应的发布任务不存在！");
            return new ResponseEntity(result, HttpStatus.OK);
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/deleteTasks", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "DELETE", value = "删除发布任务", response = Void.class, notes = "删除发布任务<br>@author zhengning")
    public ResponseEntity<?> deleteTasks(
            @RequestHeader("Authorization") String token,
            @ApiParam(value = "release_task_id 发布任务id") @RequestParam(value = "id", required = true) List<String> ids) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> result = new HashMap();
        for (String s:ids){
            ReleaseTask task = releaseTaskService.findById(s);
            if (null != task) {
                task.setDeleteFlag(DataValidity.INVALID.getState());
                releaseTaskService.save(task);
                taskStuInforService.deleteReleaseTask(s);
                result.put(ApiReturnConstants.SUCCESS, true);
            } else {
                result.put(ApiReturnConstants.SUCCESS, false);
                result.put(ApiReturnConstants.ERROR, "id对应的发布任务不存在！");
                return new ResponseEntity(result, HttpStatus.OK);
            }
        }


        return new ResponseEntity(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/exportStudentGrades", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "导出任务成绩", notes = "导出任务成绩<br>@author lwq")
    public ResponseEntity<?> exportStudentGrades(
            @ApiParam(value = "releaseTaskId 发布任务Id") @RequestParam(value = "releaseTaskId", required = true) String releaseTaskId,
            HttpServletResponse response) throws IOException {

        List<TaskResultDomain> taskResultByTaskId = releaseTaskService.findTaskResultByTaskId(releaseTaskId);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("sheet1");
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("编号");
        row.createCell(1).setCellValue("学校");
        row.createCell(2).setCellValue("姓名");
        row.createCell(3).setCellValue("专业");
        row.createCell(4).setCellValue("班级");
        row.createCell(5).setCellValue("成绩");
        row.createCell(6).setCellValue("具体分数");
        for (int i = 0; i < taskResultByTaskId.size(); i++) {
            HSSFRow row1 = sheet.createRow(i + 1);
            row1.createCell(0).setCellValue(i + 1);
            row1.createCell(1).setCellValue(taskResultByTaskId.get(i).getCollegeName());
            row1.createCell(2).setCellValue(taskResultByTaskId.get(i).getStuName());
            row1.createCell(3).setCellValue(taskResultByTaskId.get(i).getProfessionalName());
            row1.createCell(4).setCellValue(taskResultByTaskId.get(i).getClassName());
            row1.createCell(5).setCellValue(taskResultByTaskId.get(i).getResult());
            row1.createCell(6).setCellValue(taskResultByTaskId.get(i).getGrade());
        }


        FileOutputStream output = new FileOutputStream(config.getBaseDir() + "/成绩.xls");
        wb.write(output);
        output.flush();
        String basePath = config.getBaseDir() + "/成绩.xls";
        File file = new File(basePath);
        // 取得文件名。
        String filename = file.getName().toString();

        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(basePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(System.currentTimeMillis() + ".xls", "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        return new ResponseEntity(HttpStatus.OK);

    }

    @RequestMapping(value = "/findReleaseTaskQuestion", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "根据题目Id查看题目", response = Void.class, notes = "根据题目Id查看题目<br>@author lwq")
    public ResponseEntity<?> findReleaseTaskQuestion(
            @RequestHeader("Authorization") String token,
            @ApiParam(value = "releaseTaskQuestionId 发布任务问题id") @RequestParam(value = "releaseTaskQuestionId", required = true) String releaseTaskQuestionId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        QuestionAndStuAnswerDomain questionAndStuAnswer = releaseTaskQuestionsService.findQuestion(releaseTaskQuestionId);
        return new ResponseEntity(questionAndStuAnswer, HttpStatus.OK);

    }

}
